package com.zxp.cloud.storage.service.impl;

import com.zxp.cloud.storage.model.Storage;
import com.zxp.cloud.storage.repository.StorageRepository;
import com.zxp.cloud.storage.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;

/**
 * @author zxp
 * @date 2021/7/19 17:16
 */
@Service
@Slf4j
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageRepository storageRepository;

    /**
     * 减库存
     * @param productId
     * @param count
     */
    @Transactional
    @Override
    public Storage descrement(Long productId, Integer count) {
        Storage storage = storageRepository.findFirstByProductId(productId);

        if(storage!=null){
            storage.setUsed( storage.getUsed() + count );
            storage.setResidue( storage.getTotal()-storage.getUsed() );
            storageRepository.save(storage);
        }
        int i=10/0;
        return storage;
    }

    @Override
    public Storage save(Storage storage) {
        if(storage.getUsed()==null){
            storage.setUsed(0);
        }
        if(storage.getTotal()==null){
            storage.setTotal(0);
        }
        if(storage.getResidue()==null){
            storage.setResidue(storage.getTotal()-storage.getUsed());
        }
        return storageRepository.save(storage);
    }

}
